<%@ page language="java" import="java.lang.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
	String path = request.getContextPath();
%>
<div class="row-fluid" style="height: inherit;margin:0px;border: 0px">
	<form id="lineForm" class="form-horizontal" target="_ifr">
		<input type="hidden" id="id" name="id" value="${line.id}" />
		<input type="hidden" id="status" name="status" value="${line.status }" /> 
		<div class="row" style="margin:0;padding:0;">
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="lineNo">产线编号：</label>
				<div class="controls">
					<div class="input-append span12">
						<c:choose>
							<c:when test="${edit==1}">
								<input type="text" class="span11" id="lineNo" name="lineNo" value="${line.lineNo }" placeholder="产线编号" readonly="readonly">
							</c:when>
							<c:otherwise>
								<input type="text" class="span11" id="code" name="code" placeholder="后台自动生成" readonly="readonly">
							</c:otherwise>
						</c:choose>
					</div>
				</div>
			</div>
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="lineName">产线名称：</label>
				<div class="controls">
					<div class="input-append span12 required">
						<input type="text" class="span11" id="lineName" name="lineName" value="${line.lineName }" placeholder="产线名称">
					</div>
				</div>
			</div>
		</div>
		<div class="row" style="margin:0;padding:0;">
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="device">绑定设备：</label>
				<div class="controls">
					<div class="span12 required" style=" float: none !important;">
						<input type="text" class="span11" id="device" name="device" value="${line.device }" placeholder="绑定设备">
					</div>
				</div>
			</div>
			<div class="control-group span6" style="display: inline">
				<label class="control-label" for="remark">备注：</label>
				<div class="controls">
					<input type="text" class="span11" id="remark" name="remark" value="${line.remark }" placeholder="备注">
				</div>
			</div>
		</div>
		<div style="margin-left:10px;">
			<span class="btn btn-info" id="formSave" onclick="saveForm();"> 
			    <i class="ace-icon fa fa-check bigger-110"></i>保存
			</span> 
			<span class="btn btn-info" id="formSubmit" onclick="submitLine();"> 
			    <i class="ace-icon fa fa-check bigger-110"></i>&nbsp;提交
			</span>
		</div>
	</form>
	<div id="materialDiv" style="margin:10px;">
		<label class="inline" for="productId">选择产品：</label> 
		    <input type="text" id="productId" name="productId" style="width:150px;margin-right:10px;" /> 
		<label class="inline" for="artBomId">选择bom：</label> 
		    <input type="text" id="artBomId" name="artBomId" style="width:150px;margin-right:10px;" />
		<button id="addMaterialBtn" class="btn btn-xs btn-primary" onclick="addDetail();">
			<i class="icon-plus" style="margin-right:6px;"></i>添加
		</button>
	</div>
	<!-- 表格div -->
	<div id="grid-div-c" style="width:100%;margin:10px auto;">
		<!-- 	表格工具栏 -->
		<div id="fixed_tool_div" class="fixed_tool_div detailToolBar">
			<div id="__toolbar__-c" style="float:left;overflow:hidden;"></div>
		</div>
		<!-- 物料详情信息表格 -->
		<table id="grid-table-c" style="width:100%;height:100%;"></table>
		<!-- 表格分页栏 -->
		<div id="grid-pager-c"></div>
	</div>
</div>
<script type="text/javascript">
var context_path = '<%=path%>';
var lineId=$("#lineForm #id").val();
var p2p;
var oriDataDetail;
var _grid_detail;        //表格对象
var lastsel2;
var outLocationId=0;
$("#lineForm").validate({
   ignore: "", 
   rules:{
      "device":{
         required:true,
      },
      "lineName":{
         required:true,
         remote:{
            cache:false,
            async:false,
            url: "<%=path%>/productionLine/hasName?id="+$("#lineForm #id").val()
         }
      },
      "houseId":{
         required:true,
      },
   },
   messages: {
     "device":{
         required:"请选择设备！"
      },
      "lineName":{
         required:"请输入订单名称！",
         remote:"名称重复！"
      },
   },
   errorPlacement: function (error, element) {
       layer.msg(error.html(),{icon:5});
       }
});
function saveForm() {
    if ($("#lineForm").valid()) {
       saveLineInfo($("#lineForm").serialize());
    }
}
function saveLineInfo(bean) {
    $.ajax({
            url: context_path + "/productionLine/saveLine.do",
            type: "POST",
            data: bean,
            dataType: "JSON",
            success: function (data) {
                if (Boolean(data.result)) {
                    layer.msg("保存表头成功！", {icon: 1});
                    $("#lineForm #id").val(data.lineId);
                    //刷新列表
                    $("#grid-table").jqGrid("setGridParam", {
                       postData: {queryJsonString:""}
                    }).trigger("reloadGrid");
                } else {
                    layer.alert("保存失败，请稍后重试！", {icon: 2});
                }
            },
            error:function(XMLHttpRequest){
        		alert(XMLHttpRequest.readyState);
        		alert("出错啦！！！");
        	}
        });
}

  	_grid_detail=jQuery("#grid-table-c").jqGrid({
         url : context_path + "/productionLine/detailList.do?lineId="+lineId,
         datatype : "json",
         colNames : [ "详情主键","bom名称","产品名称","版本"],
         colModel : [ 
  					  {name : "id",index : "id",width : 20,hidden:true}, 
  					  {name : "bomName",index:"bomName",width :20}, 
                      {name : "productName",index:"productName",width : 20}, 
                      {name : "version",index:"version",width : 20}                     
                    ],
         rowNum : 20,
         rowList : [ 10, 20, 30 ],
         pager : "#grid-pager-c",
         sortname : "id",
         sortorder : "asc",
         altRows: true,
         viewrecords : true,
         caption : "产线详情列表",
         autowidth:true,
         multiselect:true,
		 multiboxonly: true,
         loadComplete : function(data) 
         {
             var table = this;
             setTimeout(function(){updatePagerIcons(table);enableTooltips(table);}, 0);
             oriDataDetail = data;
         },
  	     emptyrecords: "没有相关记录",
  	     loadtext: "加载中...",
  	     pgtext : "页码 {0} / {1}页",
  	     recordtext: "显示 {0} - {1}共{2}条数据",
    });
    //在分页工具栏中添加按钮
    $("#grid-table-c").navGrid("#grid-pager-c",{edit:false,add:false,del:false,search:false,refresh:false}).navButtonAdd("#grid-pager-c",{  
  	   caption:"",   
  	   buttonicon:"ace-icon fa fa-refresh green",   
  	   onClickButton: function(){   
  	    $("#grid-table-c").jqGrid('setGridParam', 
				{
  	    			url:context_path + '/transfer/detailList?transferId='+transferId,
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}
		  ).trigger("reloadGrid");
  	   }
  	});
  	
  	$(window).on("resize.jqGrid", function () {
  		$("#grid-table-c").jqGrid("setGridWidth", $("#grid-div-c").width() - 3 );
  		$("#grid-table-c").jqGrid("setGridHeight", (document.documentElement.clientHeight - $("#grid-pager-c").height() - 380) );
  	});
  	$(window).triggerHandler("resize.jqGrid");
  	if($("#id").val()!=""){
  	}
  	
  	    $("#productId").change(function () {
  	    p2p=$("#productId").val();
    })
    $("#artBomId").change(function () {
        if ($("#productId").val() == "") {
            layer.alert("请先选择产品！");
            $("#artBomId").select2("val", "");
        }
    })
        $("#productId").select2({
        placeholder: "选择产品",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/material/getMaterialSelectList",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
    $("#outLocationId").change(function(){
      outLocationId=$("#outLocationId").val();
    });
		$("#artBomId").select2({
        placeholder: "选择工艺BOM",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/productionLine/getBomList",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date(),
                    productId:$("#productId").val()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }

    });
		$("#lineForm #device").select2({
        placeholder: "选择设备",
        minimumInputLength: 0, //至少输入n个字符，才去加载数据
        allowClear: true, //是否允许用户清除文本信息
        delay: 250,
        width: 200,
        formatNoMatches: "没有结果",
        formatSearching: "搜索中...",
        formatAjaxError: "加载出错啦！",
        ajax: {
            url: context_path + "/productionLine/getDeviceId",
            type: "POST",
            dataType: "json",
            delay: 250,
            data: function (term, pageNo) { //在查询时向服务器端传输的数据
                term = $.trim(term);
                return {
                    queryString: term, //联动查询的字符
                    pageSize: 15, //一次性加载的数据条数
                    pageNo: pageNo, //页码
                    time: new Date()
                    //测试
                }
            },
            results: function (data, pageNo) {
                var res = data.result;
                if (res.length > 0) { //如果没有查询到数据，将会返回空串
                    var more = (pageNo * 15) < data.total; //用来判断是否还有更多数据可以加载
                    return {
                        results: res,
                        more: more
                    };
                } else {
                    return {
                        results: {}
                    };
                }
            },
            cache: true
        }
    });
//添加物料详情
 function addDetail(){
	  if($("#lineForm #id").val()==""){
		  layer.alert("请先保存表单信息！");
		  return;
	  }
	  if($("#outLocationId").val()==""){
	    layer.alert("请先选择产品！");
	    return;
	  }
	  if($("#inLocationId").val()==""){
	    layer.alert("请选择工艺BOM！");
	    return;
	  }
		  //将选中的物料添加到数据库中
		  $.ajax({
			  type:"POST",
			  url:context_path + "/productionLine/addDetail.do",
			  data:{lineId:$("#lineForm #id").val(),artBomId:$("#artBomId").val(),productId:$("#productId").val()},
			  dataType:"json",
			  success:function(data){
				  if(Boolean(data.result)){
					 layer.msg("添加成功",{icon:1,time:1200});
					 reloadDetailTableList();
				  }else{
					  layer.msg(data.msg,{icon:2,time:1200});
				  }
			  }
		  });
  }
  //工具栏
	  $("#__toolbar__-c").iToolBar({
	   	 id:"__tb__01",
	   	 items:[
	   	  	{label:"删除", onclick:delDetail},
	    ]
	  });
	//删除物料详情
	function delDetail(){
	   var checkedNum = getGridCheckedNum("#grid-table-c", "id");  //选中的数量
        if (checkedNum == 0) {
           layer.alert("请选择一条要删除的BOM！");
           return;
        }
	   var ids = jQuery("#grid-table-c").jqGrid("getGridParam", "selarrrow");
	   $.ajax({
	      url:context_path + "/productionLine/deleteDetail.do?ids="+ids+"&lineId="+$("#lineForm #id").val(),
	      type:"POST",
	      dataType:"JSON",
	      success:function(data){
	         if(Boolean(data.result)){
	           layer.msg(data.msg,{icon:1});
			   reloadDetailTableList();
	         }else{
	           layer.msg(data.msg,{icon:2,time:2000});
	         }
	      }
	   });
	}
	 function reloadDetailTableList(){
       $("#grid-table-c").jqGrid("setGridParam", 
				{
  	    			url:context_path + "/productionLine/detailList.do?lineId="+$("#lineForm #id").val(),
					postData: {queryJsonString:""} //发送数据  :选中的节点
				}
		  ).trigger("reloadGrid");
		}
	if($("#lineForm #id").val()!=""){
	   $.ajax({
	 type:"post",
	 url:context_path + "/productionLine/getLineById",
	 data:{id:$("#lineForm #id").val()},
	 dataType:"json",
	 success:function(data){
			  $("#lineForm #device").select2("data", {
 			  id: data.device,
 			  text: data.deviceName
             }); 
		}
	});
}
function submitLine(){
        layer.confirm("确定提交？", function() {
    		$.ajax({
    			type : "post",
    			url : context_path + "/productionLine/submit.do?lineId="+$("#lineForm #id").val(),
    			dataType : "json",
    			cache : false,
    			success : function(data) {
    				if (Boolean(data.result)) {
    					layer.msg(data.msg, {icon: 1,time:1000});
    				}else{
    					layer.msg(data.msg, {icon: 7,time:2000});
    				}
    				_grid.trigger("reloadGrid");  //重新加载表格
    			}
    		});
    	});
     }	  	
</script>
